"""
房屋价格预测系统 - 主应用程序
整合所有模块并实现完整的应用逻辑
"""

import streamlit as st
import pandas as pd

from src.data_loader import load_data, get_feature_info
from src.models import load_or_train_models
from src.visualization import (
    plot_feature_importance, 
    plot_feature_analysis, 
    plot_model_comparison,
    display_model_parameters
)
from src.ui_components import (
    create_header, create_sidebar, create_input_form, create_footer,
    display_prediction_result, create_feature_exploration_section,
    create_model_comparison_section, create_data_display_section,
    display_model_info, display_user_input, create_prediction_button,
    get_model_mapping
)
from src.config import TOP_FEATURES_COUNT


def main():
    """主应用程序入口"""
    # 设置页面配置
    st.set_page_config(
        page_title="房屋价格预测系统",
        page_icon="🏠",
        layout="wide",
        initial_sidebar_state="expanded"
    )
    
    # 创建页面头部
    create_header()
    
    # 加载数据和模型
    X, y, ids = load_data()
    model_manager = load_or_train_models()
    
    # 获取特征重要性
    feature_importance = model_manager.get_feature_importance()
    top_features = feature_importance.head(TOP_FEATURES_COUNT)['Feature'].tolist()
    
    # 创建侧边栏
    model_choice = create_sidebar()
    
    # 创建用户输入表单
    input_df = create_input_form()
    
    # 显示用户输入
    display_user_input(input_df)
    
    # 创建预测按钮
    if create_prediction_button():
        # 获取模型映射
        model_mapping = get_model_mapping()
        model_key = model_mapping[model_choice]
        
        # 进行预测
        try:
            prediction = model_manager.predict(input_df, model_key)
            model_performance = model_manager.get_model_performance(model_key)
            
            # 显示预测结果
            display_prediction_result(prediction, model_choice, model_performance)
            
        except Exception as e:
            st.error(f"预测失败: {e}")
    
    # 特征重要性分析
    st.subheader("📊 特征重要性分析")
    plot_feature_importance(feature_importance)
    
    # 数据分布探索
    explore_feature = create_feature_exploration_section(X, top_features)
    
    if explore_feature:
        # 准备数据用于可视化
        data = pd.concat([X, y], axis=1)
        if ids is not None:
            data['Id'] = ids
        
        # 绘制特征分析图表
        plot_feature_analysis(data, explore_feature)
    
    # 模型比较
    show_comparison = create_model_comparison_section()
    
    if show_comparison:
        # 计算所有模型的性能
        model_performances = {}
        for model_name in ['rf', 'svm', 'elastic']:
            perf = model_manager.get_model_performance(model_name)
            if perf:
                model_performances[model_name] = perf
        
        # 绘制模型比较图表
        plot_model_comparison(model_performances)
        
        # 显示模型参数
        display_model_parameters(model_manager.grid_searches)
    
    # 数据显示
    show_full_data = create_data_display_section()
    
    if show_full_data:
        data = pd.concat([X, y], axis=1)
        if ids is not None:
            data['Id'] = ids
        st.dataframe(data)
    
    # 显示模型信息
    feature_info = get_feature_info()
    display_model_info(
        feature_info['feature_names'],
        feature_info['sample_count'],
        top_features
    )
    
    # 创建页面底部
    create_footer()


if __name__ == "__main__":
    main()
